package com.trinity.web.controller.publicAPI.utils;


import com.github.binarywang.wxpay.v3.Validator;
import com.github.binarywang.wxpay.v3.auth.Verifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author spvycf & F00lish
 */
@Slf4j
public class WxPayValidatorForRequest {
    private final Verifier verifier;
    private final String requestId;
    private final String body;

    public WxPayValidatorForRequest(Verifier verifier, String requestId, String body) {
        this.verifier = verifier;
        this.requestId = requestId;
        this.body = body;
    }

    public final boolean validate(HttpServletRequest request) throws IOException {
        //处理请求参数
//        validateParameters(request);

        //构造验签名串
        String message = buildMessage(request);
        String serialNo = request.getHeader("Wechatpay-Serial");
        String sign = request.getHeader("Wechatpay-Signature");
        String timestamp = request.getHeader("Wechatpay-TimeStamp");
        String nonce = request.getHeader("Wechatpay-Nonce");
//        if (!verifier.verify(serialNo, message.getBytes(StandardCharsets.UTF_8), sign)) {
//            throw veriFail("serial=[%s] message=[%] sign=[%] request-id=[%]", serialNo, message, sign, requestId);
//        }
        if (timestamp == null || nonce == null || serialNo == null || sign == null) {
            return false;
        }

        return verifier.verify(serialNo, message.getBytes(StandardCharsets.UTF_8), sign);
    }

//    private void validateParameters(HttpServletRequest request) {
//        Header firstHeader = request.getHeader(requeste);
//    }

    protected final String buildMessage(HttpServletRequest request) throws IOException {
        String timestamp = request.getHeader("Wechatpay-TimeStamp");
        String nonce = request.getHeader("Wechatpay-Nonce");

//        String body = getResponseBody(request);
        return timestamp + "\n"
                + nonce + "\n"
                + body + "\n";
    }

    protected final String getResponseBody(CloseableHttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();

        return (entity != null && entity.isRepeatable()) ? EntityUtils.toString(entity) : "";
    }
}
